import React, { Component } from 'react'
import { Link, Route} from 'react-router-dom'
import Detail from './Detail'

export default class Messages extends Component {

  state = {
    messages:[
      {id:"1", title:"message 01", },
      {id:"2", title:"message 02", },
      {id:"3", title:"message 03", },
    ]
  }

  // 使按钮实现 replace 形式展示的回调函数
  replaceShow = ((id, title)=>{
    // 跳转携带 params 参数
    // this.props.history.replace(`/home/messages/detail/${id}/${title}`)
    // 跳转携带 search 参数
    // this.props.history.replace(`/home/messages/detail/?id=${id}&title=${title}`)
    // 跳转携带 state 参数
    this.props.history.replace(`/home/messages/detail`, {id:id, title:title})
  })

  // 使按钮实现 push 形式展示的回调函数
  pushShow = ((id, title)=>{
    // 跳转携带 params 参数
    // this.props.history.push(`/home/messages/detail/${id}/${title}`)
    // 跳转携带 search 参数
    // this.props.history.replace(`/home/messages/detail/?id=${id}&title=${title}`)
    // 跳转携带 state 参数
    this.props.history.replace(`/home/messages/detail`, {id:id, title:title})
  })

  // 回退回调
  back = () =>{
    this.props.history.goBack()
  }

  // 前进回调
  forword = () =>{
    this.props.history.goForward()
  }

  // 前进&回退回调
  go = ()=>{
    // 前进两步
    this.props.history.go(2)
  }

  render() {
    const {messages} = this.state
    return (
      <div className='messages'>
        <ul>
          {
            messages.map((msgObj)=>{
              return(
                <li key={msgObj.id}>
                  {/* 向路由组件传递 params 参数 */}
                  {/* <Link to={`/home/messages/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link> */}
                  {/* 向路由组件传递 search 参数 */}
                  {/* <Link to={`/home/messages/detail/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link> */}
                  {/* 向路由组件传递 state 参数 */}
                  <Link to={{pathname:'/home/messages/detail', state:{id:msgObj.id, title:msgObj.title}}}>{msgObj.title}</Link>
                  
                  <button onClick={()=>{this.pushShow(msgObj.id, msgObj.title)}}>push查看</button>
                  <button onClick={()=>{this.replaceShow(msgObj.id, msgObj.title)}}>replace查看</button>
                </li>
              )
            })
          }
        </ul>
        {/* 声明接收 params 参数 */}
        {/* <Route path='/home/messages/detail/:id/:title' component={Detail}/> */}
        {/* 声明接收 search 参数, 正常注册路由即可 */}
        {/* <Route path='/home/messages/detail' component={Detail}/> */}
        {/* 声明接收 state 参数, 正常注册路由即可 */}
        <Route path='/home/messages/detail' component={Detail}/>

        <button onClick={this.forword}>前进</button>
        <button onClick={this.back}>回退</button>
      </div>
    )
  }
}
